package service

import (
	"context"
	"encoding/json"
	"errors"
	"fx_swift_boss/api"
	"fx_swift_boss/internal/model"
	"fx_swift_boss/pkg/code"
	"fx_swift_boss/pkg/global"
	"fx_swift_boss/pkg/gorsa"
	"fx_swift_boss/pkg/httputils"
	"fx_swift_boss/pkg/internalerrors"
	"fx_swift_boss/pkg/logger"
	"fx_swift_boss/pkg/utils"
	"github.com/gogf/gf/v2/frame/g"
	"io"
	"net/http"
)

// 卡片信息修改(状态)
func EditCardStatus(ctx context.Context, req *api.EditCardStatusReq) error {
	var (
		err            error
		url            = "/api/vas/card/modifyCard"
		dataContent    string
		pubdecrypt_str string
		resp           *api.EditCardStatusRes
		statusDesc     string
	)
	req.UserReqNo = utils.GetHashCode(utils.GenerateCode32())
	dataContent, err = OperatorParams(global.ViperObj.GetString("gep.url")+url, req)
	if err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	// 公钥解密
	pubdecrypt_str, err = gorsa.PublicDecrypt(dataContent, gorsa.GetPublicKeyStr())
	if err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	err = json.Unmarshal([]byte(pubdecrypt_str), &resp)
	if err != nil {
		return internalerrors.New(code.ErrUnknown, err.Error())
	}
	if len(pubdecrypt_str) != 0 {
		if req.Status == "1" {
			statusDesc = "使用中"
		} else if req.Status == "0" {
			statusDesc = "冻结"
		}
		if _, err = global.GFDB.Ctx(ctx).Schema("card").Model("fx_card_info").Data(g.Map{
			"card_status":      req.Status,
			"card_status_desc": statusDesc,
		}).Where("card_id=?", req.CardId).Update(); err != nil {
			logger.SugarLogger.Error(err.Error())
			return internalerrors.New(code.ErrUnknown, "卡信息修改失败")
		}
	}
	return err
}

func GetCardImage(ctx context.Context, cardId string) (*api.GetCardImageRes, error) {
	var (
		err    error
		url    = "/api/vas/card/v2/img"
		resp   = &api.GetCardImageRes{}
		respVo *api.GetCardImageVo
		body   []byte
	)
	body, err = json.Marshal(&api.GetCardImageReq{
		CardId: cardId,
	})
	respVo, err = SendRequestToGepToJson(global.ViperObj.GetString("gep.url")+url, string(body))
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	resp.CardImgBack = respVo.CardImgBack
	resp.CardImgFront = respVo.CardImgFront
	return resp, err
}

// 获取comply平台accessToken
func GetComplyToken(ctx context.Context) (string, error) {
	var (
		url  = global.ViperObj.GetString("comply.baseUrl") + "/v1/token"
		err  error
		resp *http.Response
		body []byte
		obj  api.ComplyAuthRes
	)
	//组装请求header参数
	headers := map[string]string{
		"content-type": "application/json",
		"accept":       "*/*",
	}

	//组装请求body参数
	reqObj := &api.ComplyAuthReq{
		UserName: global.ViperObj.GetString("comply.userName"),
		PassWord: global.ViperObj.GetString("comply.passWord"),
		Realm:    global.ViperObj.GetString("comply.realm"),
	}
	body, err = json.Marshal(&reqObj)
	//请求cc银行接口获取token
	resp, _ = httputils.HTTPPost(url, headers, body)
	if resp.StatusCode != 200 {
		return "", errors.New("获取accessToken失败")
	}

	body, err = io.ReadAll(resp.Body)
	err = json.Unmarshal(body, &obj)
	if err != nil {
		logger.SugarLogger.Errorf("json 读取报错：%w", err)
		return "", err
	}
	//token写入redis，并设置过期时间
	if err = g.Redis().SetEX(ctx, global.ViperObj.GetString("comply.tokenFlag")+global.ViperObj.GetString("comply.userName"), "Bearer "+obj.AccessToken, global.ViperObj.GetInt64("token.comply_expired_time")); err != nil {
		return "", internalerrors.New(code.ErrUnknown, err.Error())
	}
	return obj.AccessToken, nil
}

// 请求comply创建kyc记录
func DoPostCompanyComply(ctx context.Context, req *api.ComplyCompanyOnboardingReq) (string, error) {
	var (
		url         = global.ViperObj.GetString("comply.baseUrl") + "/v1/workflows/create-and-screen"
		err         error
		resp        *http.Response
		body        []byte
		obj         api.ComplyOnboardingRes
		accessToken string
	)
	//获取token
	accessToken, err = GetComplyTokenToRedis(ctx)
	if err != nil {
		logger.SugarLogger.Errorf("读取token失败：%w", err)
		return "", internalerrors.New(code.ErrUnknown, "读取token失败")
	}
	//组装请求header参数
	headers := map[string]string{
		"content-type":  "application/json",
		"accept":        "application/json",
		"authorization": accessToken,
	}

	body, err = json.Marshal(&req)
	//请求cc银行接口获取token
	resp, _ = httputils.HTTPPost(url, headers, body)
	if resp.StatusCode != 200 {
		return "", errors.New("提交客户记录失败")
	}

	body, err = io.ReadAll(resp.Body)
	err = json.Unmarshal(body, &obj)
	if err != nil {
		logger.SugarLogger.Errorf("ComplyOnboardingRes读取报错：%w", err)
		return "", err
	}
	return obj.WorkflowInstanceIdentifier, nil
}

// 请求comply创建kyc记录
func DoPostPersonComply(ctx context.Context, req *model.ComplyPersonOnboardingReq) (string, error) {
	var (
		url         = global.ViperObj.GetString("comply.baseUrl") + "/v1/workflows/create-and-screen"
		err         error
		resp        *http.Response
		body        []byte
		obj         api.ComplyOnboardingRes
		accessToken string
	)
	//获取token
	accessToken, err = GetComplyTokenToRedis(ctx)
	if err != nil {
		logger.SugarLogger.Errorf("读取token失败：%w", err)
		return "", internalerrors.New(code.ErrUnknown, "读取token失败")
	}
	//组装请求header参数
	headers := map[string]string{
		"content-type":  "application/json",
		"accept":        "application/json",
		"authorization": accessToken,
	}

	body, err = json.Marshal(&req)
	//请求cc银行接口获取token
	resp, _ = httputils.HTTPPost(url, headers, body)
	if resp.StatusCode != 200 {
		return "", errors.New("提交客户记录失败")
	}

	body, err = io.ReadAll(resp.Body)
	err = json.Unmarshal(body, &obj)
	if err != nil {
		logger.SugarLogger.Errorf("ComplyOnboardingRes读取报错：%w", err)
		return "", err
	}
	return obj.WorkflowInstanceIdentifier, nil
}
